package banner

import (
	"context"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateBannerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBannerLogic {
	return &CreateBannerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateBannerLogic) CreateBanner(req *types.CreateBannerReq) (resp *types.BaseMsgResp, err error) {
	if (req.PicUrl == nil || len(strings.TrimSpace(*req.PicUrl)) == 0) && len(req.NewMedia) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "banner.picUrlRequired"))
	}

	if req.StartedAt == nil || len(strings.TrimSpace(*req.StartedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "banner.startedAtRequired"))
	}

	if req.EndedAt == nil || len(strings.TrimSpace(*req.EndedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "banner.endedAtRequired"))
	}

	newThumbMap := make(map[string]*types.MediaInfo)
	var newMediaIds []string // 用于查询 attachmentRpc
	var thumbnail *uint32 = pointy.GetPointer(uint32(1))
	var newMedia []*backendclient.MediaInfo
	var newAttachmentIds []string // 用于主动通知 attachmentRpc
	if len(req.NewThumb) > 0 {    // 封面图
		for _, v := range req.NewThumb {
			if v.Id != nil && len(*v.Id) > 0 {
				if _, ok := newThumbMap[*v.Id]; !ok { // 忽略重复id
					newThumbMap[*v.Id] = v
					newMediaIds = append(newMediaIds, *v.Id)
				}
			} else {
				newMedia = append(newMedia, &backendclient.MediaInfo{
					Order:    v.Order,
					Url:      v.Url,
					Name:     v.Name,
					MimeType: v.MimeType,
					AltText:  v.AltText,
					MetaData: v.MetaData,
				})
			}
		}
	}

	if len(newMediaIds) > 0 {
		res, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
			Ids: pointy.GetPointer(strings.Join(newMediaIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				if v.Id != nil && len(*v.Id) > 0 {
					if item, ok := newThumbMap[*v.Id]; ok {
						var url string
						if v.Url != nil && len(*v.Url) > 0 {
							url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *v.Url)
						}
						if len(url) == 0 && v.Path != nil && len(*v.Path) > 0 {
							url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *v.Path)
						}
						newMedia = append(newMedia, &backendclient.MediaInfo{
							Id:        v.Id,
							Thumbnail: thumbnail,
							Order:     item.Order,
							Uri:       item.Url,
							Url:       pointy.GetPointer(url),
							Name:      item.Name,
							MimeType:  item.MimeType,
							AltText:   item.AltText,
							MetaData:  item.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, *v.Id)
					}
				}
			}
		}
	}

	var bannerType *uint32
	if req.Type != nil && *req.Type > 0 {
		bannerType = req.Type
	} else {
		bannerType = pointy.GetPointer(uint32(globalkey.SettingBannerTypeWechatMiniIndex))
	}
	var adId *uint64
	var adType *uint32
	if req.LinkType != nil && *req.LinkType > 0 { // 相对路径，接收广告类型和广告ID
		adType = req.AdType
		adId = req.AdId
	}

	res, err := l.svcCtx.BackendRpc.CreateBanner(l.ctx, &backendclient.BannerInfo{
		PicUrl:    req.PicUrl,
		Type:      bannerType,
		Title:     req.Title,
		LinkType:  req.LinkType,
		LinkUrl:   req.LinkUrl,
		AdType:    adType,
		AdId:      adId,
		Status:    req.Status,
		Sort:      req.Sort,
		StartedAt: req.StartedAt,
		EndedAt:   req.EndedAt,
		NewMedia:  newMedia,
	})
	if err != nil {
		return
	}

	if len(newAttachmentIds) > 0 {
		_, err = l.svcCtx.AttachmentRpc.CreateFileLog(l.ctx, &attachmentclient.CreateFileLogReq{
			FileIds:    newAttachmentIds,
			Put:        pointy.GetPointer(uint32(1)),
			ObjectId:   pointy.GetPointer(res.Id),
			ObjectType: pointy.GetPointer(uint32(globalkey.AttachmentLogTypeBanner)),
		})
		if err != nil {
			logx.Errorw("CreateBanner CreateFileLog err", logx.Field("detail", err.Error()))
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
